//
//  MHComicCommentViewController.m
//  ManHua
//
//  Created by 江子安 on 15/10/26.
//  Copyright © 2015年 蓝欧科技. All rights reserved.
//

#import "MHComicCommentViewController.h"
#import "MHComicCommentTableViewCell.h"
#import <AFNetworking.h>
#import "MHReplyListVC.h"
#import "MHComicCommentViewController.h"
#import "MJRefresh.h"
#import "MHUserInfoSington.h"
#import "MHLoginViewController.h"
#define kCommentURL @"http://112.124.96.190:9090/bukamanhua5appjobs/ComicHandle.ashx"
#import <AFNetworking.h>


@interface MHComicCommentViewController ()<UITextFieldDelegate,UITableViewDataSource, UITableViewDelegate>

@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) NSMutableArray *dataSourceArr;

@property (nonatomic, strong) UITextField *inputTF;// 评论输入框
@property (nonatomic, strong) UIButton *commentBtn;
@property (nonatomic, strong) UIView *inputView;
@property(nonatomic,assign)NSInteger pageIndex;
@property(nonatomic,strong)NSMutableArray *hotArr;
@property(nonatomic,strong)NSMutableArray *commentArr;
@property(nonatomic,strong)NSMutableArray *sectionNameArr;
@property(nonatomic,strong)UIView *sectionView;
@property(nonatomic,strong)UIButton *sectionName;
@end

@implementation MHComicCommentViewController

- (void)dealloc
{
    [[NSNotificationCenter defaultCenter]removeObserver:self];
}
-(NSMutableArray *)sectionNameArr
{
    if (_sectionNameArr==nil) {
        self.sectionNameArr=[NSMutableArray arrayWithObjects:@"热门评论",@"最新评论",nil];
    }
    
    return _sectionNameArr;
}
-(NSMutableArray *)hotArr
{
    if (_hotArr==nil) {
        self.hotArr=[NSMutableArray arrayWithCapacity:0];
        
    }
    return _hotArr;
}
-(NSMutableArray *)commentArr
{
    if (_commentArr ==nil) {
        self.commentArr=[NSMutableArray arrayWithCapacity:0];
    }
    return _commentArr;
}
- (NSMutableArray *)dataSourceArr
{
    if (!_dataSourceArr) {
        _dataSourceArr = [NSMutableArray arrayWithCapacity:0];
        
    }
    return _dataSourceArr;
}

-(void)AcquirecommentData
{
    NSMutableDictionary *dict2 = [NSMutableDictionary dictionaryWithCapacity:0];
    
    dict2[@"uuid"] = @"537e76184314b8c8beb37f75bacafb14edbe0d97";
    dict2[@"method"] = @"commentlist"; // 最新的时commentlist   "hotcommentlist"
    dict2[@"bookid"] = self.bookid;
    dict2[@"pageindex"]=[NSString stringWithFormat:@"%ld",(long)self.pageIndex];
    if (self.pageIndex==0) {
        [self.commentArr  removeAllObjects];
    }
    
    [[AFHTTPRequestOperationManager manager] GET:kCommentURL parameters:dict2 success:^(AFHTTPRequestOperation * _Nonnull operation, id  _Nonnull responseObject) {
        
        NSArray *arr = responseObject;
        for (NSDictionary *dict in arr) {
            MHComicComentModel *model = [[MHComicComentModel alloc]init];
            [model setValuesForKeysWithDictionary:dict];
            if (self.commentArr.count<self.commentCount) {
                [self.commentArr  addObject:model];
            }
            
        }
        
        [self.tableView.header endRefreshing];
        [self.tableView.footer endRefreshing];
        [self.tableView reloadData];
        
        
    } failure:^(AFHTTPRequestOperation * _Nonnull operation, NSError * _Nonnull error) {
        NSLog(@"%@",error.localizedDescription);
    }];
    
    
}

- (void)requestHotData
{
    NSMutableDictionary *dict1 = [NSMutableDictionary dictionaryWithCapacity:0];
    
    dict1[@"uuid"] = @"537e76184314b8c8beb37f75bacafb14edbe0d97";
    dict1[@"method"] = @"hotcommentlist"; // 最新的时commentlist   "hotcommentlist"
    dict1[@"bookid"] = self.bookid;
    
    
    
    
    [self.hotArr removeAllObjects];
    
    [[AFHTTPRequestOperationManager manager] GET:kCommentURL parameters:dict1 success:^(AFHTTPRequestOperation * _Nonnull operation, id  _Nonnull responseObject) {
        
        NSArray *arr = responseObject;
        for (NSDictionary *dict in arr) {
            MHComicComentModel *model = [[MHComicComentModel alloc]init];
            [model setValuesForKeysWithDictionary:dict];
            
            [self.hotArr addObject:model];
        }
        
        
        
    } failure:^(AFHTTPRequestOperation * _Nonnull operation, NSError * _Nonnull error) {
        NSLog(@"%@",error.localizedDescription);
    }];
    
    
    
}


// 添加一个输入框
- (void)addCommentInputView
{
    _inputView = [[UIView alloc]initWithFrame:CGRectMake(0, Height - 40, Width, 40)];
    _inputView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:_inputView];
    
    _inputTF = [[UITextField alloc]initWithFrame:CGRectMake(15, 5, Width - 30 - 60 - 15, 30)];
    _inputTF.delegate = self;
    _inputTF.borderStyle = UITextBorderStyleRoundedRect;
    _inputTF.placeholder = @"写评论...";
    [_inputView addSubview:_inputTF];
    
    _commentBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    _commentBtn.frame = CGRectMake(_inputTF.frame.size.width + 30, 5, 60, 30);
    _commentBtn.backgroundColor = [UIColor colorWithRed:0.246 green:0.922 blue:0.204 alpha:1.000];
    [_commentBtn setTitle:@"评论" forState:UIControlStateNormal];
    [_commentBtn addTarget:self action:@selector(submitCommentButton:) forControlEvents:UIControlEventTouchUpInside];
    [_inputView addSubview:_commentBtn];
    
}
-(void)submitCommentButton:(UIButton *)button
{
    NSUserDefaults *user=[NSUserDefaults standardUserDefaults];
    if ([user boolForKey:@"isLogin"]) {
#pragma mark- 把设备的信息上传上去
        NSInteger userID=  [MHUserInfoSington sharedInstance].userInfo.UserID;
        
        NSLog(@"%ld",userID);
        UIDevice *currentDevice = [UIDevice  currentDevice];
        NSLog(@"%@",currentDevice.name);
        NSString *bundleName=@"布丁漫画";
        
        NSString *pathString = [NSString stringWithFormat:@"http://112.124.96.190:9090/bukamanhua5appjobs/ComicHandle.ashx?clientType=%@&bundleID=com.yuansen.ManHuaZhuo44&userID=%ld&token=&appleLanguages=zh-Hans&method=postdevicetoken&version=5.0&realtoken=&bundleName=%@",currentDevice.name,userID,bundleName];
        
        NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:pathString] cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:10.0];
        [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue currentQueue] completionHandler:^(NSURLResponse * _Nullable response, NSData * _Nullable data, NSError * _Nullable connectionError) {
            if (connectionError!=nil) {
                NSLog(@"数据请求出错了%@",connectionError);
            }
            else
            {
                NSString *result=[[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
                NSLog(@"%@",result);
                if ([result isEqualToString:@"1"]) {
                    NSLog(@"请求成功");
                    
                    
                }
            }
        }];
#pragma mark -上传评论
        NSString *filePathString=[NSString stringWithFormat:@"http://112.124.96.190:9090/bukamanhua5appjobs/ComicHandle.ashx?method=insertnewcomment&userid=%ld&bookid=%@&client=15&content=%@",userID,self.bookid,[_inputTF.text stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
        
        NSURLRequest *request2 = [NSURLRequest requestWithURL:[NSURL URLWithString:filePathString] cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:10.0];
        [NSURLConnection sendAsynchronousRequest:request2 queue:[NSOperationQueue currentQueue] completionHandler:^(NSURLResponse * _Nullable response, NSData * _Nullable data, NSError * _Nullable connectionError) {
            if (connectionError!=nil) {
                NSLog(@"数据请求出错了%@",connectionError);
            }
            else
            {
                NSString *result=[[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
                if ([result isEqualToString:@"1"]) {
                    NSLog(@"请求成功");
                     [self.inputTF resignFirstResponder];
                    [self requestHotData];
                    [self AcquirecommentData];
                    [self.tableView reloadData];
                    
                   
                    
                    
                }
            }
        }];


    }
    else
    {
        MHLoginViewController *loginVC = [[MHLoginViewController alloc]init];
        loginVC.successLoginBlock=^
        {
            
        };
        [self.navigationController pushViewController:loginVC animated:YES];
    }
}
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.pageIndex=0;
    // 评论需要请求两个数据。
    [self requestHotData ];
    [self AcquirecommentData];
    self.automaticallyAdjustsScrollViewInsets = NO;
    
    _tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 64, SCREEN_WIDTH, SCREEN_HEIGHT - 40 - 64) style:UITableViewStylePlain];
    _tableView.delegate = self;
    _tableView.dataSource = self;
    
    _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    __weak MHComicCommentViewController *test = self;
    _tableView.header=[MJRefreshNormalHeader headerWithRefreshingBlock:^{
        test.pageIndex=0;
        [test requestHotData ];
        [test AcquirecommentData];
        
    }];
    [_tableView.header beginRefreshing];
    _tableView.footer=[MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        test.pageIndex++;
        if (test.commentCount <= test.commentArr.count) {
            [_tableView.footer endRefreshingWithNoMoreData];
        }
        else
        {
            [test AcquirecommentData];
        }
    }];
    [_tableView.footer beginRefreshing];
    [_tableView registerClass:[MHComicCommentTableViewCell class] forCellReuseIdentifier:@"cell"];
    
    [self.view addSubview:_tableView];
    [self addCommentInputView];
    
    
    // 给键盘添加监控
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(keyboardWillChangeFrame:) name:UIKeyboardWillChangeFrameNotification object:nil];
    
}

#pragma mark - 文本框代理
/**
 *  点击了return按钮(键盘最右下角的按钮)就会调用
 */
- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [self.view endEditing:YES];
    // 返回YES即可
    return YES;
}
/**
 *  当键盘改变了frame(位置和尺寸)的时候调用
 */
- (void)keyboardWillChangeFrame:(NSNotification *)note
{
    
    
    // 0.取出键盘动画的时间
    CGFloat duration = [note.userInfo[UIKeyboardAnimationDurationUserInfoKey] doubleValue];
    
    // 1.取得键盘最后的frame
    CGRect keyboardFrame = [note.userInfo[UIKeyboardFrameEndUserInfoKey] CGRectValue];
    
    // 2.计算控制器的view需要平移的距离
    CGFloat transformY = keyboardFrame.origin.y - self.view.frame.size.height;
    
    // 3.执行动画
    [UIView animateWithDuration:duration animations:^{
        self.view.transform = CGAffineTransformMakeTranslation(0, transformY);
    }];
}
/**
 *  当开始拖拽表格的时候就会调用
 */
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
{
    // 退出键盘
    [self.view endEditing:YES];
}


- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (self.hotArr.count != 0) {
        if (indexPath.section==0)
        {
            MHComicComentModel *model = self.hotArr[indexPath.row];
            return [MHComicCommentTableViewCell heightOfCellWithModdel:model];
            
        }
        
    }
    if (self.commentArr.count != 0) {
        if (indexPath.section==1)
        {
            MHComicComentModel *model=self.commentArr[indexPath.row];
            return [MHComicCommentTableViewCell heightOfCellWithModdel:model];
        }
    }
    return 0;
    
    
}
-(NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
    return self.sectionNameArr[section];
    
}
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 2;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (section==0) {
        return self.hotArr.count;
    }
    else
    {
        return self.commentArr.count;
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    MHComicCommentTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell" forIndexPath:indexPath];
    if (indexPath.section==0) {
        MHComicComentModel *model = self.hotArr[indexPath.row];
        [cell configureDataWithModel:model];
        
    }
    else
    {
        MHComicComentModel *model = self.commentArr[indexPath.row];
        [cell configureDataWithModel:model];
    }
    return cell;
}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    if (indexPath.section==0) {
        MHComicComentModel *model = self.hotArr[indexPath.row];
        
        MHReplyListVC *replyListVC = [[MHReplyListVC alloc]init];
        
        replyListVC.commentid = [NSString stringWithFormat:@"%@",model.CommentID];
        replyListVC.replyCount=[model.ReplyCount integerValue];
        [self.navigationController pushViewController:replyListVC animated:YES];
        
    }
    else
    {
        MHComicComentModel *model = self.commentArr[indexPath.row];
        
        MHReplyListVC *replyListVC = [[MHReplyListVC alloc]init];
        
        replyListVC.commentid = [NSString stringWithFormat:@"%@",model.CommentID];
        replyListVC.replyCount=[model.ReplyCount integerValue];
        [self.navigationController pushViewController:replyListVC animated:YES];
        
        
    }
    
    
    
}


- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    
    self.sectionView=[[UIView alloc]initWithFrame:CGRectMake(0, 0,100,Width/24)];
    self.sectionView.backgroundColor=[UIColor clearColor];
    self.sectionName=[[UIButton alloc ]initWithFrame:CGRectMake(-10, 0,Width / 4,25)];
    [self.sectionName setTitle:self.sectionNameArr[section] forState:UIControlStateNormal] ;
    self.sectionName.titleLabel.font=[UIFont systemFontOfSize:12];
    UIImage *image = [UIImage imageNamed:@"redBtn2@3x.jpg"];
    UIImage *btnImg =  [image resizableImageWithCapInsets:UIEdgeInsetsMake(image.size.height/2,image.size.width/2, image.size.height/2, image.size.width/2)];
    self.sectionName.layer.cornerRadius = 12;
    self.sectionName.layer.masksToBounds = YES;
    [self.sectionName setBackgroundImage:btnImg forState:UIControlStateNormal];
    self.sectionName.titleLabel.textColor=[UIColor whiteColor];
    
    [self.sectionView  addSubview:self.sectionName];
    
    
    
    return self.sectionView;
}



- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

@end
